package com.iussoft.receiveData.service.plugins;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.apache.api.vo.ParamsVo;
import com.apache.api.vo.ResultEntity;
import com.apache.exception.BusinessException;
import com.apache.tools.DateUtils;
import com.apache.tools.StrUtil;
import com.iussoft.receiveData.schedul.SendService;
import com.iussoft.tools.*;
import org.springframework.stereotype.Service;

/**
 * @description: 主动抓取数据实现
 * @author: Hou Dayu
 * @date: Created in 2020/3/12
 */
@Service("synchronize-data")
public class SynchronizeDataPluginconnector extends SuperPluginconnector {

    @Override
    public Object execute(ParamsVo vo) throws Exception {
        ResultEntity result = new ResultEntity();
        String dxpInterfaceInfo = vo.getParamsToStr("dxpInterfaceInfo");
        JSONObject data = JSON.parseObject(dxpInterfaceInfo);
        JSONObject interfaceInfo = getInterfaceInfo(data.getString("fromServerId"));
        RequestMessage reqMsg =(RequestMessage)vo.getObj();
        JSONObject json = new JSONObject();
        String topic = getKafkaTopic(1);
        result.setResult("true");
        String key ="0";
        String resultData = null;
        json.put("ifTest",interfaceInfo.getString("ifTest"));
        if("1".equals(interfaceInfo.getString("ifTest"))){
            resultData = interfaceInfo.getString("dataTest");
        } else {
            //interfaceInfo.put("ifLayOut","1");
            if("1".equals(interfaceInfo.getString("ifLayOut"))){//是否是编排服务
                JSONArray arrays = (JSONArray)dataReceiveManager.execute(interfaceInfo,reqMsg,vo.getParamsToStr("traceId"),interfaceInfo.getString("exchangeMode"),topic);
                if(arrays != null && !arrays.isEmpty()){
                    for(int i=0;i<arrays.size();i++) {
                        JSONObject jsobj = arrays.getJSONObject(i);
                        String msg = jsobj.getString("sourceMsg");
                        if(StrUtil.isNull(msg)){
                            continue;
                        }
                        JSONObject jsons = new JSONObject();
                        jsons.put("ifTest",interfaceInfo.getString("ifTest"));
                        if(jsobj.containsKey("mergeParams")){
                            jsons.put("mergeParams",jsobj.get("mergeParams"));
                        }
                        if(jsobj.containsKey("defaultColumn")){//默认列
                            jsons.put("defaultColumn",jsobj.get("defaultColumn"));
                        }
                        sendMessage(jsons, jsobj.getString("sourceMsg"), reqMsg.getInfoByKey("requestPwd"), interfaceInfo, vo);
                        resultData = jsobj.getString("sourceMsg");
                    }
                }
            } else {
                try {
                    resultData = sendDataMsg(vo.getParamsToStr("traceId"), json, interfaceInfo, reqMsg);
                    if (StrUtil.isNull(resultData)) {
                        throw new BusinessException("接口数据返回空");
                    }
                } catch (BusinessException e) {
                    result.setMessage("获取" + interfaceInfo.getString("interfaceUri") + "接口失败，错误信息为: " + e.getMessage());
                    LoggerUtil.infoSource("exception = {}; infoType = exception; traceId = {}; interfaceCode = {}; requestTime = {}; errorMessage = {}; requestIp = {}; exeSys = receive; level = {}",e.getClass().getSimpleName(), vo.getParamsToStr("traceId"), interfaceInfo.getString("interfaceCode"), DateUtils.Now.fmt_yyyyMMdd_HHmmss(),result.getMessage(),vo.getParamsToStr("requestUseIp"),"ERROR");
                    return result;
                }
                sendMessage(json,resultData,reqMsg.getInfoByKey("requestPwd"), interfaceInfo, vo);
            }
            LoggerUtil.infoSource("tarceId = {}; interfaceCode = {}; 抓取数据成功",vo.getParamsToStr("traceId"),vo.getParamsToStr("requestCode"));
        }
        if (sendMsgTool.isJson(resultData)) {
            result.setEntity(JSON.parseObject(resultData));
        } else {
            result.setEntity(resultData);
        }
        result.setMessage("数据接收成功");
        return result;
    }

    /**
     * 同步数据
     */
    private void sendMessage(JSONObject json, String msg,String requestPwd , JSONObject interfaceInfo, ParamsVo vo){
        json.put("sourceMsg", msg.replaceAll("\n", "").replaceAll("\r", ""));
        json.put("sendTime", System.currentTimeMillis());
        json.put("interfaceCode", interfaceInfo.getString("interfaceCode"));
        json.put("infterfaceId", interfaceInfo.getString("infoId"));
        json.put("sysEname", interfaceInfo.getString("sysEname"));
        json.put("infterfacePwd", requestPwd);
        json.put("traceId", vo.getParamsToStr("traceId"));
        json.put("requestUseIp", vo.getParamsToStr("requestUseIp"));
        json.put("requestCode", vo.getParamsToStr("requestCode"));
        json.put("dataType", "resp");
        if(kafkaSimpleSender.getKafkaEnabled()) {
            String topic = getKafkaTopic(1);
            String key ="0";
            kafkaSimpleSender.sendMsg(topic, key, json.toJSONString());
        } else {
            dynamicTask.submitRun(new SendService(json));
        }
    }
}
